/**
 * 
 */
package com.csair.youth.service.impl;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.csair.youth.constant.ResourceConstant;
import com.csair.youth.database.Category;
import com.csair.youth.domain.TreeNode;

/**
 * @author mickey
 *
 */
public class CategoryGenerateJobServiceImpl {
	private static final Logger log = Logger.getLogger(CategoryGenerateJobServiceImpl.class);
	private static final SimpleDateFormat fullDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	private CategoryServiceImpl categoryService;
	private int storeRootPathLen = 0;
	
	public CategoryServiceImpl getCategoryService() {
		return categoryService;
	}

	public void setCategoryService(CategoryServiceImpl categoryService) {
		this.categoryService = categoryService;
	}

	public void scanAndGenerateCategories(){
		log.warn("ftp目录自动同步器于"+fullDateFormat.format(new Date())+"运行...");
		Map<String, TreeNode> categoryTree = categoryService.buildCategoryTree(null, false);
		TreeNode root = categoryTree.get("ROOT");
		Map<TreeNode, String> existPaths = categoryService.getCategoryPathsUnique(root);
		String storeRootPath = ResourceConstant.getInstance().getUploadStorePath();
		storeRootPathLen = storeRootPath.length();
		File storePath = new File(storeRootPath);
		DirFilter filter = new DirFilter();
		if(storePath.exists()){
			scanAndGenerateWhenHasNew(storePath, existPaths, root.getId(), filter);
		}
		else{
			log.error("根存储目录不存在，跳过扫描");
		}
	}
	
	/**
	 * 递归
	 * @param path
	 * @param nodeAndPath
	 * @param parentId
	 * @param filter
	 */
	private void scanAndGenerateWhenHasNew(File path, Map<TreeNode, String> nodeAndPath, String parentId, DirFilter filter){
		String currentPath = null;
		try {
			currentPath = path.getCanonicalPath();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("扫描过程中获取路径出错:"+path.getName());
		}
		if(currentPath != null){
			String currentShortPath = currentPath.substring(storeRootPathLen);
			if(!currentShortPath.equals("")){
				//不是根目录
				Set<TreeNode> keys = nodeAndPath.keySet();
				if(keys != null){
					Iterator<TreeNode> iter = keys.iterator();
					boolean found = false;
					while(iter.hasNext()){
						TreeNode key = iter.next();
						String keyPath = nodeAndPath.get(key);
						if(StringUtils.equals(keyPath, currentShortPath)){
							parentId = key.getId();
							found = true;
							break;
						}
					}
					if(!found){
						//不存在，需要新增
						Category newCategory = new Category();
						newCategory.setName(path.getName());
						newCategory.setDescription(path.getName()+"(ftp创建)");
						newCategory.setParentId(parentId);	//应该不可能为空，因为root节点不会进来这里
						categoryService.saveCategory(newCategory);
						parentId = newCategory.getId();
						log.warn("新分类自动创建了:"+newCategory.getId()+","+newCategory.getName());
					}
				}
			}
			File subdirs[] = path.listFiles(filter);
			if(subdirs != null){
				for(int i=0; i<subdirs.length; i++){
					scanAndGenerateWhenHasNew(subdirs[i], nodeAndPath, parentId, filter);
				}
			}
		}
	}
	
	
}

class DirFilter implements FileFilter{
	public boolean accept(File pathname) {
		// TODO Auto-generated method stub
		if(pathname.isDirectory()) return true;
		else return false;
	}
	
}
